package com.mysoft.quartz.job;

import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
public class ResetJob {

	@Autowired
	@Qualifier(value = "schedule")
	private Scheduler scheduler;

//	public void doSomething() {
//		System.out.println("want to reset job");
//	}

	public void addJob(String className, String cronExpression) throws Exception {
		//TriggerKey triggerKey = new TriggerKey("simpleTrigger", Scheduler.DEFAULT_GROUP);
		//SimpleTriggerImpl simpleTrigger = (SimpleTriggerImpl) scheduler.getTrigger(triggerKey);
		// 重置时间间隔
		//simpleTrigger.setRepeatInterval(time);
		// 重启job
		//scheduler.rescheduleJob(triggerKey, simpleTrigger);
		
//		String className = "com.mysoft.quartz.job.MyJob3";
//		String cronExpression = "0/10 * * * * ?";
		
		Class clazz = Class.forName(className);
		JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity("JobDetail:" + className, Scheduler.DEFAULT_GROUP).build();
		
		CronTriggerImpl cronTrigger = new CronTriggerImpl();
		cronTrigger.setName("JobTrigger:" + className);
		cronTrigger.setCronExpression(cronExpression);
		
		scheduler.scheduleJob(jobDetail, cronTrigger);
	}
	
	public void pause(String className) throws Exception{
		JobKey jobKey = new JobKey("JobDetail:" + className, Scheduler.DEFAULT_GROUP);
		scheduler.pauseJob(jobKey);
	}
	
	public void resume(String className) throws Exception{
		JobKey jobKey = new JobKey("JobDetail:" + className, Scheduler.DEFAULT_GROUP);
		scheduler.resumeJob(jobKey);
	}
	
	public void stop(String className) throws Exception{
		JobKey jobKey = new JobKey("JobDetail:" + className, Scheduler.DEFAULT_GROUP);
		scheduler.deleteJob(jobKey);
	}
}
